package de.arndt_plc.wakeonmagic;

import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by MathiasAr on 24.10.2014.
 */
public class IpHelper {

    public static final String TAG = IpHelper.class.getSimpleName();

    /**
     * ARP cache (/proc/net/arp).<br>
     * <br>
     * We assume that the file has this structure:<br>
     * <br>
     * IP address       HW type     Flags       HW address            Mask     Device
     * 192.168.18.11    0x1         0x2         00:04:20:06:55:1a     *        eth0
     * 192.168.18.36    0x1         0x2         00:22:43:ab:2a:5b     *        eth0
     *
     * @return IP and MAC map of all ARP entries.
     */
    public static Map<InetAddress, String> getArpMap() throws IOException {
        Map<InetAddress, String> checkMapARP = new HashMap<InetAddress, String>();
        BufferedReader localBufferedReader = new BufferedReader(new FileReader(new File("/proc/net/arp")));
        String line = "";

        while ((line = localBufferedReader.readLine()) != null) {
            String[] lineSplit = line.split("[ ]+");
            String ip = lineSplit[0];
            String mac = lineSplit[3];
            if (mac.matches("..:..:..:..:..:..")) {
                // check ip address
                try {
                    InetAddress ipAddress = InetAddress.getByName(ip);
                    if (!checkMapARP.containsKey(ipAddress)) {
                        Log.d(TAG, "Found ARP entry: " + ip + " " + mac);
                        checkMapARP.put(ipAddress, mac);
                    }
                } catch (UnknownHostException uh) {
                    Log.d(TAG, uh.getMessage(), uh);
                }
            }
        }
        localBufferedReader.close();
        return Collections.unmodifiableMap(checkMapARP);
    }


}
